Ext.define('App.commons.echarts.XYChart', {
    extend: 'App.commons.echarts.EchartsPanel',
    alias: ['widget.XYChart'],
    constructor: function (config) {
        var chartConfiguration = config.chartConfiguration;
        var datas = config.reportDatas;
        var kpis = config.kpis;


        var option = this.createOption(chartConfiguration, datas, kpis);

        Ext.apply(config, {
            //初始化基础属性
            option: option,
            height: chartConfiguration.height || 400,
            columnWidth: chartConfiguration.width || .5,
        });
        this.callParent(arguments);
    },
    createOption: function (chartConfiguration, datas, kpis) {
        var colors = {
            customtheme: ["#c23531", "#2f4554", "#61a0a8", "#d48265", "#91c7ae", "#749f83", "#ca8622", "#bda29a", "#6e7074", "#546570", "#c4ccd3"],
            shine: ["#e6b600", "#0098d9", "#c12e34", "#2b821d", "#005eaa", "#339ca8", "#cda819", "#32a487"]
        };

        var me = this;
        var axis = Ext.Array.findBy(chartConfiguration.axes, function (item) {
            if (item.type == 'category' && item.position == 'bottom') {
                return true;
            }
            return false;
        });
        var xAxisDatas = []
        Ext.Array.each(datas, function (item) {
            if (axis.fields == '迭代') {
                xAxisDatas.push('迭代' + item[axis.fields]);
            } else {
                xAxisDatas.push(item[axis.fields]);
            }
        })

        var xAxis = [{
            type: 'category',
            name: axis.title,
            data: xAxisDatas,
            axisLabel: {
                formatter: function (value, index) {
                    return value
                }
            },
            //x轴交点为一组数据
            axisPointer: {
                type: 'shadow'
            }
        }];

        var yAxis = [];
        Ext.Array.each(chartConfiguration.axes, function (item) {
            if (item.position != 'bottom') {
                yAxis.push({
                    nameLocation: 'middle',
                    nameGap: 40,
                    fields: item.fields.replace(/\s/g, '').split(','),
                    type: item.type == 'numeric' ? 'value' : '',
                    position: item.position,
                    name: Ext.isEmpty(item.title) ? item.fields : item.title,
                    axisLine: {
                        lineStyle: {
                            color: 'gray'
                        }
                    },
                    axisLabel: {
                        formatter: function (value, index) {
                            if (item.percent == true) {
                                return (value) + '%'
                            }
                            return value;
                        }
                    }
                });
            }
        })


        var legend = {
            //图例，与series的name对应
            data: [],
            y: 'bottom',    //延Y轴居中
            x: 'center' //居右显示
        }
        var series = [];
        Ext.Array.each(chartConfiguration.series, function (item) {
            var fields = item.yFields;
            if (!Ext.isArray(fields) && fields != 'null') {
                fields = fields.replace(/\s/g, '')
                fields = fields.split(',')
            }
            for (var i = 0; i < fields.length; i++) {
                var field = fields[i];
                var yAxisDatas = []
                Ext.Array.each(datas, function (data) {
                    var value = data[field];
                    if (item.percent == true) {
                        value = data[field] = data[field] * 100;
                    }
                    if (Ext.isNumeric(value)) {
                        value = Ext.util.Format.number(value, '########.##')
                    }
                    yAxisDatas.push(value);
                })
                series.push({
                    barMaxWidth: 60,
                    name: field,
                    type: item.type,
                    data: yAxisDatas,
                    yAxisIndex: me.findYAxisIndex(yAxis, field),
                    // markPoint: {
                    //     data: [
                    //         {type: 'max', name: '最大值'},
                    //         {type: 'min', name: '最小值'}
                    //     ]
                    // },
                    label: {show: true}
                    // markLine: {
                    //     data: [
                    //         {type: 'average', name: '平均值'}
                    //     ]
                    // }
                });
                legend.data.push(field)
            }
        });

        var option = {
            color: colors[chartConfiguration.theme] || colors.customtheme,
            title: {
                text: chartConfiguration.title || '',
                subtext: chartConfiguration.description || ""
            },
            toolbox: {
                show: true,
                right: 40,
                top: 20,
                feature: {
                    dataView: {
                        title: '数据',
                        show: true,
                        readOnly: false,
                        backgroundColor: '#efefef',
                        optionToContent: function (opt) {
                            var datas = [];
                            var rows = 0;
                            var html = "<style>";
                            html += ".echart-dataview{border-left:1px solid gray;border-top:1px solid gray;margin:auto;}";
                            html += ".echart-dataview td{border-right:1px solid gray;border-bottom:1px solid gray;height:25px;}";
                            html += ".echart-dataview th{border-right:1px solid gray;border-bottom:1px solid gray;height:28px;background:#999;}";
                            html += "</style>";
                            html += '<table class="echart-dataview" style="width:95%;text-align:center;" cellspacing="0" cellpadding="0"><thead><tr>';
                            var axes = opt.xAxis;
                            //创建表头
                            Ext.Array.each(axes, function (axis) {
                                html += '<th>' + axis.name + '</th>';
                                datas.push(axis.data);
                                if (axis.data.length > rows) {
                                    rows = axis.data.length;
                                }
                            })

                            var series = opt.series;
                            Ext.Array.each(series, function (item) {
                                html += '<th>' + item.name + '</th>';
                                datas.push(item.data);
                            })
                            html += '</tr></thead>';


                            html += '</tbody>';

                            var lines = axes.length + series.length;
                            for (var i = 0; i < rows; i++) {
                                html += '<tr>';
                                for (var j = 0; j < lines; j++) {
                                    var value = datas[j][i];
                                    console.log(value + '=' + (typeof  value));
                                    if (Ext.isEmpty(value) || (typeof  value == 'number' && isNaN(value))) {
                                        value = "";
                                    }
                                    html += '<td>' + value + '</td>';
                                }
                                html += '</tr>';
                            }
                            html += '</tbody></table>';
                            return html;
                        }
                    },
                    magicType: {show: true, type: ['line', 'bar']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            tooltip: {
                trigger: 'axis',
                //当前鼠标位置使用虚线划出来
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: 'red'
                    }
                }
            },
            grid: {
                top: 90,
                left: 30,
                right: 30,
                bottom: 40,
                containLabel: true
            },
            calculable: true,
            legend: legend,
            xAxis: xAxis,
            yAxis: yAxis,
            series: series
        };
        return option;
    },
    findYAxisIndex: function (yAxis, field) {
        for (var i = 0; i < yAxis.length; i++) {
            if (Ext.Array.contains(yAxis[i].fields, field)) {
                return i;
            }
        }
        return -1;
    }
})